<script setup lang="ts">
import { getRoleListApi, delRoleApi, addRoleApi, getRoleDetailApi, updateRoleApi, assginPermApi } from '@/api/setting'
import { ref, onMounted } from 'vue'
import type { SettingListParam, SettingResult, AddSettingParam, AddSettingResult } from '@/types/setting'
import { Edit, Delete } from '@element-plus/icons-vue'
// @ts-ignore
import PaginationIndex from '@/views/Setting/components/PaginationIndex.vue'
import { ElMessageBox, ElMessage, ElTree } from 'element-plus'
import { ElForm } from 'element-plus'
import { useUserStore } from '@/store/user'
import type { CompanyInfo } from '@/types/company'
// @ts-ignore
import { getCompanyInfoApi } from '@/api/company'
import { getPersmissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import type { PermissionItem } from '@/types/permission'

// 请求参数
const params = ref<SettingListParam>({
  page: 1,
  pagesize: 5
})
const loading = ref(false)
// 获取角色列表数据
const result = ref<SettingResult>()
// 获取数据总条数
const total = ref(0)
const getRoleList = async () => {
  loading.value = true
  const res = await getRoleListApi(params.value)
  result.value = res.data
  total.value = res.data.total
  loading.value = false
}

// 计算每页数据的序号
const indexMethod = (index: number) => {
  return (params.value.page - 1) * params.value.pagesize + index + 1
}

// 删除功能
const deleteRole = async (id: string) => {
  // 提示用户 是否要删除
  await ElMessageBox.confirm('此操作将永久删除该文件，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await delRoleApi(id)
  // 提示用户 删除成功
  ElMessage.success('删除成功')
  // 重新获取数据
  // 判断删除的数据是不是最后一页的最后一条数据
  if (params.value.page > 1 && result.value?.rows.length === 1) {
    params.value.page--
  }
  getRoleList()
}

// dialog 弹框模块
//控制弹框隐藏展示 变量
const dialogVisible = ref(false)
//展示添加弹框
const showAddRoleDialog = () => {
  dialogVisible.value = true
}
const closeDialog = () => {
  dialogVisible.value = false
}

// 收集表单数据
const formModel = ref<AddSettingParam>({
  name: '',
  description: ''
})
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
// dialog title 标题
const title = ref('')
// 表单校验
const rules = ref({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ]
})
// 添加角色
const addRole = () => {
  // 清空表单
  formModel.value = { name: '', description: '' }
  showAddRoleDialog()
  title.value = '新增角色'
}

// 点击确定按钮 添加 或 编辑
const submitRole = async () => {
  // 表单校验
  await formRef.value?.validate()
  if (title.value === '新增角色') {
    await addRoleApi(formModel.value)
    // 跳转到最后一页
    params.value.page = Math.ceil(total.value / params.value.pagesize)
  } else {
    await updateRoleApi(RoleDetail.value)
  }
  ElMessage.success('操作成功')
  closeDialog()
  getRoleList()
}

// 编辑角色
const editRole = (id: string) => {
  showAddRoleDialog()
  title.value = '修改角色'
  // 获取要编辑的角色数据
  getRoleDetail(id)
}
// 获取角色详情
const RoleDetail = ref<AddSettingResult>({
  id: '',
  name: '',
  description: '',
  permIds: []
})
const getRoleDetail = async (id: string) => {
  const res = await getRoleDetailApi(id)
  // 表单数据回显
  RoleDetail.value = res.data
  // 回显表单数据
  formModel.value.description = res.data.description
  formModel.value.name = res.data.name
}

// 获取公司信息
const { userInfo } = useUserStore()
const companyInfo = ref<CompanyInfo>()
const getCompanyInfo = async () => {
  const res = await getCompanyInfoApi(userInfo?.companyId as string)
  companyInfo.value = res.data
}

// 获取 tree 实例
const treeRef = ref<InstanceType<typeof ElTree>>()
// 控制分配权限弹框 显示和隐藏
const dialogVisible2 = ref(false)
// loading 效果
const isLoading = ref(false)
// 获取 点击的角色id
const assginId = ref('')
// 获取权限列表
const permissionList = ref<PermissionItem[]>()
// 打开分配权限弹框
const opendialogVisible2 = async (id: string) => {
  isLoading.value = true
  assginId.value = id
  dialogVisible2.value = true
  // 回显所有权限列表
  const res = await getPersmissionListApi()
  permissionList.value = transListToTreeData<PermissionItem>(res.data, '0')
  isLoading.value = false
  // 回显当前角色的权限
  const result = await getRoleDetailApi(id)
  treeRef.value?.setCheckedKeys(result.data.permIds || [])
}
//配置el-tree的属性 矫正接口字段
const defaultProps = {
  children: 'children',
  label: 'name'
}
// 关闭权限弹框
const closedialogVisible2 = () => {
  dialogVisible2.value = false
}

// 点击权限的确定按钮
const confirmAssiginRole = async () => {
  // 获取 勾选数据的 id
  const checkedKeys = treeRef.value?.getCheckedKeys() as string[]
  await assginPermApi({ id: assginId.value, permIds: checkedKeys || [] })
  ElMessage.success('分配权限成功')
  dialogVisible2.value = false
  // 重新获取数据
  getRoleList()
}

onMounted(() => {
  getRoleList()
  getCompanyInfo()
})
</script>
<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button type="primary" @click="addRole">
              <el-icon> <Plus /> </el-icon>新增角色</el-button
            >
            <!-- 表格 -->
            <el-table :data="result?.rows" v-loading="loading">
              <el-table-column label="序号" width="100" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="success" @click="opendialogVisible2(row.id)">分配权限</el-button>
                  <el-button type="primary" :icon="Edit" @click="editRole(row.id)">编辑</el-button>
                  <el-button type="danger" :icon="Delete" @click="deleteRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pager" style="margin-top: 10px; display: flex; justify-content: flex-end">
              <!-- 分页 pagination -->
              <pagination-index
                v-if="total"
                v-model:currentPage="params.page"
                v-model:pageSize="params.pagesize"
                :total="total"
                @update:pageSize="getRoleList"
                @update:currentPage="getRoleList"
                background
                style="margin-top: 40px; justify-content: flex-end"
              ></pagination-index>
            </div>
          </el-tab-pane>

          <!-- 获取公司信息模块 -->
          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改" type="info" show-icon :closable="false" />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input disabled style="width: 400px" :value="companyInfo?.name" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input disabled style="width: 400px" :value="companyInfo?.companyAddress" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input disabled style="width: 400px" :value="companyInfo?.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :rows="3" disabled style="width: 400px" :value="companyInfo?.remarks" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- dialog 弹框 -->
      <el-dialog v-model="dialogVisible" @close="closeDialog" :title="title" width="30%">
        <el-form label-width="100px" :model="formModel" :rules="rules" ref="formRef">
          <el-form-item label="角色名称" prop="name">
            <el-input placeholder="请输入角色名称" v-model="formModel.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input placeholder="请输入角色描述" v-model="formModel.description" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="submitRole">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog title="分配权限" v-model="dialogVisible2" :close-on-click-modal="false">
        <el-tree
          ref="treeRef"
          v-loading="isLoading"
          show-checkbox
          default-expand-all
          node-key="id"
          check-strictly
          highlight-current
          :data="permissionList"
          :props="defaultProps"
        >
        </el-tree>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closedialogVisible2">取消</el-button>
            <el-button type="primary" @click="confirmAssiginRole">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<style scoped></style>
